/**
 * learn react-redux functions
 * Provider 提供state到组件的注入
 * connect 连接redux与组件
 */

import React from 'react';
import { createStore, combineReducers, bindActionCreators } from 'redux';
import { Provider,connect } from 'react-redux';

//create reducer1
const counter = (state = { count: 0 }, action) => {
  switch (action.type) {
    case 'ADD':
      return { count: state.count + 1 }
    case 'REDUCE':
      return { count: state.count - 1 }
    default:
      return state
  }
}

//create reducer2
const todos = (state = { text: '吃饭' }, action) => {
  return state
}

//combine all reducers
const reducers = combineReducers({
  counter,
  todos
})


//create store[传入单个reducer或者reducers合集]
const store = createStore(reducers);


//create action
function add() {
  return {
    type: 'ADD'
  }
}

function reduce() {
  return {
    type: 'REDUCE'
  }
}


class Counter extends React.Component {
  render() {
    const { count,todos, add, reduce } = this.props;
    return (
      <div>
        <h3>c2-react-redux</h3>
        <h4>count add/reduce</h4>
        <h5>todos：{todos.text}</h5>
        <hr />
        <div className="flex">
          <span className="icon" onClick={reduce}> - </span>
          <input className="input" value={count} />
          <span className="icon" onClick={add}> + </span>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  console.log('state:',state)
  return {
    count: state.counter.count,
    todos: state.todos
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ add, reduce }, dispatch)
}

const ConnectedCounter = connect(mapStateToProps, mapDispatchToProps)(Counter)

class C2 extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <ConnectedCounter />
      </Provider>
    )
  }
}


export default C2